package cpa.prowon.gui.image;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;

import cpa.prowon.image.ImageContainer;
import cpa.prowon.image.Thumbnail;
import cpa.prowon.image.ThumbnailManager;

/**
 * Creates a thumbnail in an own thread
 * @author Chris
 */
public class ThumbnailDisplayer extends Thread {

	// Properties
	private ImageContainer _ic;
	private Canvas _canvas;
	private Image _image;
	
	/**
	 * Return the canvas
	 * @return The canvas where the thumbnail will be shown
	 * @author Chris
	 */
	public Canvas getCanvas() {
		return _canvas;
	}

	/**
	 * Constructor
	 * @param ImageContainer The image container the holds the reference to the image
	 * @param Canvas The canvas where the thumbnail shall be shown
	 * @author Chris
	 */
	public ThumbnailDisplayer(ImageContainer ic, Canvas canvas) {
		_ic = ic;
		_canvas = canvas;
	}
	
	public void run() {
		
		// Be lazy and sleep some time. In case the user scrolls over the images, the thread
		// will anyway be interrupted
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			return;
		}

		// Try to get the thumbnail from the image registry before creating a new one, if it's not
		// available there, create one		
		Display.getDefault().syncExec(new Runnable() {
			public void run() {
			_image = ThumbnailManager.getInstance().getThumbnail(_ic);
			}
		});
		if (_image == null) {
			
			// Create the thumbnail
			Thumbnail thumb = new Thumbnail(_ic);
			_image = thumb.getImage();
			
			// Put the thumbnail into the image registry, hopefully thread safe
			Display.getDefault().syncExec(new Runnable() {
				public void run() {
					ThumbnailManager.getInstance().cacheThumbnail(_ic, _image);
				}
			});
			
		}

		// Force the canvas to redraw, hopefully thread safe
		if (!this.isInterrupted()) {
		Display.getDefault().syncExec(new Runnable() {
			public void run() {
				_canvas.redraw();
			}
		});
		}
		
	}

}
